<script setup>
import * as Cesium from 'cesium'
import { onMounted, ref } from 'vue'
import ToggleControl from '@/components/ToggleControl.vue'
import MyPrimitive from '@/primitives/MyPrimitive.js'
import PyramidPrimitive from '@/primitives/PyramidPrimitive.js'
import CirclePrimitive from '@/primitives/CirclePrimitive.js'
import WaterPrimitive from '@/primitives/WaterPrimitive.js'
import FlagPrimitive from '@/primitives/FlagPrimitive'
import addEntity from '@/utils/addEntity'
import add3DTiles from '@/utils/add3DTiles'
import addWater from "@/utils/addWater.js"
import addRadar from "@/utils/addRadar.js"

let viewer, baseLayer, enumLayer
const tianditutkArr = ['590447cdbdf97775b57588a69ebb903d', '75f1cc913e8d68f7bd4b6f6383f78ceb', '4c4c0f03b0bdb58811f657fec0c09eb5']
// ['590447cdbdf97775b57588a69ebb903d', '75f1cc913e8d68f7bd4b6f6383f78ceb', '4c4c0f03b0bdb58811f657fec0c09eb5']
const tianditutk = tianditutkArr[Math.floor(Math.random() * tianditutkArr.length)]
Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhZjE5ZTBhZC00YzE1LTQyMWYtOWM4MC00NmFlZjZhOGI3ZDciLCJpZCI6MTI4NTI2LCJpYXQiOjE2OTg4MzczOTN9.26EHXec7Ufty_B4e5_YWcB0t--zlquly7r66WVSS9wE'
// 设置Cesium默认视角
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(108.4, 21.3, 129.3, 48.6)

const isMask = ref(false)
// 是否打开功能列表
const isToggle = ref(false)
let bgMask
// 添加摄像头遮罩效果
const addMask = (viewer) => {
  if(!isMask.value) {
    const fs =
    `
    uniform sampler2D colorTexture;
    uniform sampler2D maskTexture;
    in vec2 v_textureCoordinates;
    void main() {
      vec4 color = texture(colorTexture, v_textureCoordinates);
      float mask = texture(maskTexture, v_textureCoordinates).a;
      out_FragColor = vec4(color.rgb * (1.0 - mask) * 1.3, 1.0);
    }`
    // 巧用postProcessStage后处理实现自定义渲染效果
    bgMask = viewer.scene.postProcessStages.add(new Cesium.PostProcessStage({
        fragmentShader : fs,
        uniforms : {
          maskTexture: 'mask.png'
        }
    }))
    isMask.value = true
  }
}
// 移除摄像头遮罩效果
const removeMask = (viewer) => {
  if(isMask.value) {
    viewer.scene.postProcessStages.remove(bgMask)
    isMask.value = false
  }
  bgMask = undefined
}
// 添加图层遮罩效果
const addMaskEntity = (viewer) => {
  let mask = new Cesium.Entity({
    polygon: {
      hierarchy: {
        //添加外部区域为1/4半圆，设置为180会报错
        positions: Cesium.Cartesian3.fromDegreesArray([0, 0, 0, 90, 179, 90, 179, 0]),
        //中心挖空的“洞”
        holes: [
          {
            positions: Cesium.Cartesian3.fromDegreesArray([118.4, 31.3, 118.4, 38.6, 129.3, 38.6, 129.3, 31.3]),
            // holes: []
          }
        ]
      },
      material: new Cesium.ColorMaterialProperty(Cesium.Color.GRAY.withAlpha(0.6))
    }
  })
  viewer.entities.add(mask)
}
// 添加地球点击事件
const addClickEvent = (viewer) => {
  let windowPosition
  const canvas = viewer.scene.canvas
  const mouseHandler = new Cesium.ScreenSpaceEventHandler(canvas)
  // 绑定鼠标左点击事件
  mouseHandler.setInputAction((e) => {
    console.log(e)
    windowPosition = e.position   // 屏幕坐标
    // 屏幕坐标转笛卡尔坐标
    const ray = viewer.camera.getPickRay(windowPosition)
    const catesian = viewer.scene.globe.pick(ray, viewer.scene)
    // 笛卡尔坐标转经纬度坐标
    const lat = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(catesian).latitude)
    const lng = Cesium.Math.toDegrees(Cesium.Cartographic.fromCartesian(catesian).longitude)
    console.log('当前经度坐标是:' + lng + ';纬度坐标是:' + lat)
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
onMounted(() => {
  baseLayer = new Cesium.ImageryLayer(new Cesium.WebMapTileServiceImageryProvider({
    url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" + tianditutk,
    layer: "tdtImgLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
    show: true
  }))
  viewer = new Cesium.Viewer('cesiumContainer', {
    animation: false,   // 动画小组件
    baseLayerPicker: false,  // 底图组件，选择三维数字地球的底图
    fullscreenButton: false,  // 全屏组件
    vrButton: false,    // VR模式
    geocoder: false,    // 地理编码搜索组件
    homeButton: false,  // 首页，点击之后将视图跳转到默认视角
    infoBox: false,     // 信息框
    sceneModePicker: false,  // 场景模式，切换2D、3D和Columbus Views（CV）模式
    selectionIndicator: false,  // 是否显示选取指示器组件
    timeline: false,    // 时间轴
    navigationHelpButton: false,    // 帮助提示，如何操作数字地球
    navigationInstructionsInitiallyVisible: false,
    // terrain: new Cesium.Terrain.fromWorldTerrain({
    //   url: Cesium.IonResource.fromAssetId(3956),
    //   requestWaterMask: true,    // 请求水体效果所需要的海水波浪数据
    //   requestVertexNormals: true   // 请求地形照明数据
    // }),
    baseLayer,
    contextOptions: {
      requestWebgl2: true  // 开启webgl2渲染
    }
  })
  
  enumLayer = new Cesium.ImageryLayer(new Cesium.WebMapTileServiceImageryProvider({
    url: "http://t0.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=" + tianditutk,
    layer: "tdtCiaLayer",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",//使用谷歌的瓦片切片方式
    show: true
  }))
  viewer.imageryLayers.add(enumLayer)
  // 开启深度测试，控制视角不转到地下
  viewer.scene.globe.depthTestAgainstTerrain = true
  window.baseLayer = baseLayer
  window.viewer = viewer
  window.enumLayer = enumLayer
  // addMask(viewer)
  // addMaskEntity(viewer)
  console.log(new Cesium.PerInstanceColorAppearance())
  // viewer.scene.primitives.add(new MyPrimitive())
  // viewer.scene.primitives.add(new PyramidPrimitive())
  // viewer.scene.primitives.add(new CirclePrimitive())
  // viewer.scene.primitives.add(new WaterPrimitive())
  viewer.scene.primitives.add(new FlagPrimitive())
  // addClickEvent(viewer)
  // addEntity()
  // add3DTiles()
  // addWater()
  addRadar()
})
</script>

<template>
  <div id="cesiumContainer">
    <h3>Cesium三维地球</h3>
    <button class="toggle-button" @click="isToggle = !isToggle">打开功能列表</button>
  </div>
  <toggle-control v-if="isToggle"></toggle-control>
</template>

<style lang="scss">
#cesiumContainer {
  width: 100vw;
  height: 100vh;
  position: relative;

  .cesium-viewer-bottom {
    visibility: hidden;
  }

  h3 {
    position: absolute;
    top: 30px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 24px;
    color: #fff;
    z-index: 1000;
  }

  .toggle-button {
    position: absolute;
    top: 100px;
    left: 50px;
    cursor: pointer;
    z-index: 1000;
  }
}
</style>
